<?php
/**
 * Created by PhpStorm.
 * User: tairy
 * Date: 2019/4/29
 * Time: 14:51
 */

namespace Core\Common\Argus\Interceptor;

use Core\Common\Base\Job;
use Core\Common\Route\Request;
use Core\Common\Util\Helper;

class ArgusInterceptor
{
    public static function handleRequest($event = 'un')
    {
        $logEntry = [
            'trace_id' => Request::traceId(),
            'span_id' => Request::spanId(),
            'event' => $event,
            'server_name' => Helper::getHostName(),
            'service_name' => CORE_NAME,
            'timestamp' => Helper::getMillisecond(),
            'endpoint' => Request::uri(),
            'method' => Request::method()
        ];

        self::recordLog($logEntry);
    }

    public static function handleHttpExec($event = 'un', $spanId = '0.1', $payload = [])
    {
        $logEntry = [
            'trace_id' => Request::traceId(),
            'span_id' => $spanId,
            'event' => $event,
            'server_name' => Helper::getHostName(),
            'service_name' => CORE_NAME,
            'timestamp' => Helper::getMillisecond(),
            'endpoint' => $payload['uri'] ?? '',
            'method' => $payload['method'] ?? ''
        ];

        self::recordLog($logEntry);
    }

    public static function recordLog($logEntry = [])
    {
        if (empty($logEntry)) {
            return;
        }

        $logStr = json_encode($logEntry) . PHP_EOL;
        Job::fire('log', 'all', $logStr, 'argus_');
    }
}